package com.tan.kotlintest.changeskin;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.tan.kotlintest.R;

public class TestSetFactory2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        testChangeOne();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_set_factory2_layout);
    }

    /**
     * 测试只替换一个控件
     * 注意: setFactory2方法
     * (1) setFactory2方法应该在setContentView()之前调用
     * (2) 如果是在AppCompatActivity中调用, 最好是在super.onCreate(savedInstanceState)之前调用;
     * 因为会报错: 调用过setFactory2之后  mFactorySet 就会为true,再次调用就会抛出异常
     * if (mFactorySet) {
     * throw new IllegalStateException("A factory has already been set on this LayoutInflater");
     * }
     * (3) 其中原因是:AppCompatActivity在onCreate的时候调用了setFactory2,具体代码流程:
     * delegate.installViewFactory() -> AppCompatDelegateImplV9.installViewFactory() ->
     * if (layoutInflater.getFactory() == null) {
     * LayoutInflaterCompat.setFactory2(layoutInflater, this);
     * }
     * <p>
     * (4) 至于为何会调用setFactory2, 是为了将xml中的TextView等替换成AppCompactTextView这总
     * 具体在: AppCompatViewInflater createView()中可看到
     *
     * <p>
     * 也可以在super.onCreate(savedInstanceState)之后调用, 那就是用反射把mFactorySet修改为false
     */
    private void testChangeOne() {
        LayoutInflater.from(TestSetFactory2Activity.this).setFactory2(new LayoutInflater.Factory2() {
            //
            @Override
            public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
                if (name.contains("TextView")) {
                    ImageView imageView = new ImageView(getApplicationContext());
                    imageView.setBackgroundResource(R.drawable.image_2);
                    return imageView;
                }
                return null;
            }

            //在这个方法中执行好像不行,可能是
            //setFactory2之后,mFactory2不为空了,就只走了onCreateView(View parent, String name, Context context, AttributeSet attrs)
            //mFactory的onCreateView(String name, Context context, AttributeSet attrs)就不走了
            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                /*if (name.contains("TextView")) {
                    ImageView imageView = new ImageView(getApplicationContext());
                    imageView.setBackgroundResource(R.drawable.image_2);
                    return imageView;
                }*/
                return null;
            }
        });
    }

}
